﻿$(document).ready(function () {

    var $homeBanners = $('.homeBanners'),
		$hotSales = $('.hotSales'),
		$invitation = $('.invitation'),
		carousels = {};

    // init home banners carousel
    $homeBanners.owlCarousel({
        slideSpeed: 300,
        paginationSpeed: 400,
        singleItem: true,
        pagination: true,
        navigation: true,
        autoPlay: 7000

    });
    carousels.homeBanners = $homeBanners.data('owlCarousel');

    // init hot sales carousel
    $hotSales.owlCarousel({
        slideSpeed: 300,
        paginationSpeed: 400,
        singleItem: true,
        pagination: false,
        navigation: true,
        mouseDrag: false,
        touchDrag: false,
        afterMove: function (elem) {
            var $hotSalesNavs = $('.hotSalesNav a');
            $hotSalesNavs.removeClass('active');
            $hotSalesNavs.eq(carousels.hotSales.currentItem).addClass('active');
        }

    });
    carousels.hotSales = $hotSales.data('owlCarousel');
    $('.hotSalesNav a').on('click', function (e) {
        e.preventDefault();

        var $this = $(this),
			x = $(this).parent().index();
        $('.hotSalesNav a').removeClass('active');
        $this.addClass('active');
        carousels.hotSales.goTo(x);
    });

    // init selections horizontal accordion
    $('.selection').zAccordion({
        easing: 'jswing',
        auto: true,
        speed: 500,
        timeout: 4000,
        slideWidth: 765,
        startingSlide: 4,
        width: 1200,
        height: 467
    });

    // init invitation carousel
    $invitation.owlCarousel({
        slideSpeed: 300,
        paginationSpeed: 400,
        items: 3,
        pagination: false,
        navigation: true,
        mouseDrag: false,
        touchDrag: false

    });
    carousels.invitation = $invitation.data('owlCarousel');

    //init date picker
    // moment.locale('zh-cn');
    // $('.datePicker').pikaday({ firstDay: 1 });
    $('.datePicker').datepicker({
	    format: 'yyyy-mm-dd',
        language: 'zh-CN',
        weekStart: 0,
	    orientation: 'top left',
	    startDate: '+1d'
    });
    $('.input-daterange').datepicker({
	    format: 'm月d日',
        language: 'zh-CN',
	    weekStart: 0,
	    orientation: 'top left'

    });


    // init navigation
    // $('.navigation .level1 > li').hover(function(){
    // 	$this = $(this);
    // 	$this.find('.level2').slideDown('medium');
    // }, function(){
    // 	$this = $(this);
    // 	$this.find('.level2').slideUp('medium');
    // });
    // init search panel
    var widgetSearchPanel = {
        $searchForm: $('.searchForm'),
        $trigger: $('#keyword'),
        $panel: $('.searchPanel'),
        $close: $('.searchPanel .close'),
        activeClass: 'open',
        init: function () {
            var _this = this;
            _this.$searchForm.on('focusin click', function (e) {
                _this.open();
            });
            // .on('focusout', function(e){
            // 	setTimeout(function(){
            // 		if(!$.contains(_this.$searchForm[0], document.activeElement)){
            // 			_this.close();
            // 		}
            // 	}, 50);
            // });

            _this.$close.on('click', function (e) {
                e.preventDefault();
                e.stopPropagation();
                _this.close();
            });
            $(document.body).on('click', function (e) {
                if ($('.datepicker-dropdown').length) return;

                var $target = $(e.target);
                setTimeout(function () {
                    if (!$.contains(_this.$searchForm[0], $target[0])) {
                        _this.close();
                    }
                }, 50);

            });

            $('.navigation .level1 > li').on('mouseenter', function () {
                _this.close();
            });
        },
        open: function () {
            this.$panel.addClass(this.activeClass);
        },
        close: function () {
            this.$panel.removeClass(this.activeClass);

        }

    };
    widgetSearchPanel.init();

    // smooth scroll
    $('a[href*=#]:not([href=#]):not([aria-controls])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 500);
                return false;
            }
        }
    });

    // hide back to top button when we are at the top
    $(window).on('scroll', function (e) {
        $backTopBtn = $('.backToTop');
        if ($(window).scrollTop() > 0) {
            $backTopBtn.css('display', 'block');
        } else {
            $backTopBtn.css('display', 'none');
        }
    });

    // show/hide level4 navigations
    $('.discover .level4').prev().on('click', function (e) {
        e.preventDefault();
        $this = $(this);
        if ($this.next().hasClass('visible')) {
            $this.next().removeClass('visible');
        } else {
            $('.discover .level4.visible').removeClass('visible');
            $this.next().toggleClass('visible');
        }

    });

    // init tabs widget
    $('.nav-tabs a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });

    // init carousel for product banner
    $('.productBannerImages').owlCarousel({
        slideSpeed: 300,
        paginationSpeed: 400,
        singleItem: true,
        pagination: true,
        autoPlay: true

    });

    // init carousel for hotel images
    $('.hotelImages .owl-carousel').owlCarousel({
        slideSpeed: 300,
        paginationSpeed: 400,
        singleItem: true,
        pagination: true,
        autoPlay: true

    });

    // init carousel for brilliant products
    $('.BrilliantProducts').owlCarousel({
        slideSpeed: 300,
        paginationSpeed: 400,
        items: 3,
        pagination: false,
        navigation: true,
        mouseDrag: false,
        touchDrag: false,
        responsive: false

    });

    $(".partnersList").simplyScroll();

    // init tooltip
    if (!($('html').hasClass('ie6') ||
		$('html').hasClass('ie7') ||
		$('html').hasClass('ie8'))) {
        $('[data-toggle="tooltip"]').tooltip();
    }

    // client prefer native embed video
    // $("#jquery_jplayer_1").jPlayer({
    // 	ready: function () {
    // 		$(this).jPlayer("setMedia", {
    // 			title: "Big Buck Bunny",
    // 			m4v: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v",
    // 			ogv: "http://www.jplayer.org/video/ogv/Big_Buck_Bunny_Trailer.ogv",
    // 			webmv: "http://www.jplayer.org/video/webm/Big_Buck_Bunny_Trailer.webm",
    //                poster: "../images/content/productDetails/productVideo.jpg"
    // 		});
    // 	},
    // 	swfPath: "../scripts/libs/jPlayer",
    // 	supplied: "webmv, ogv, m4v",
    // 	size: {
    // 		width: "823px",
    // 		height: "463px",
    // 		cssClass: "productIntroductionVideo"
    // 	},
    // 	useStateClassSkin: true,
    // 	autoBlur: false,
    // 	smoothPlayBar: true,
    // 	keyEnabled: true,
    // 	remainingDuration: true,
    // 	toggleDuration: true,
    // 	pause: function () {
    //         $(this).parent().find('.jp-video-play').show();
    //     },
    //     play: function () {
    //         $(this).parent().find('.jp-video-play').hide();
    //     }
    // });

    // local data demo
    var arrDestination = [
			'大马士革／DaMaShiGe',
			'马萨达／MaSaDa',
			'马塞马拉／MaSaiMaLa',
			'哈马马特／HaMaMaTe',
			'马特马他／MaTeMaTa',
			'马尔代夫／MaErDaiFu',
			'马来西亚／MaLaiXiYa',
			'马尼拉／MaNiLa'
    ];
    $('#searchByDestination').typeahead({
        source: arrDestination
    });

    // ajax data demo
    // $.get('/data/countries.json', function(data){
    //     $("#searchByDestination").typeahead({ 
    //     	source:data 
    //     });
    // },'json');


    if (!($('html').hasClass('ie6') ||
		$('html').hasClass('ie7'))) {
        $('.modal .radioButton input, .modal .checkbox input').iCheck({
            checkboxClass: 'icheckbox_minimal',
            radioClass: 'iradio_minimal'
        });
    }

    // placeholder polyfill
    //2015-10-27 jquery.placeholder.min.js不加载报错所以注释掉
    //$('input, textarea').placeholder();

    // $('.collapse').collapse({toggle: false});
    if ($('html').hasClass('ie6') ||
		$('html').hasClass('ie7') ||
		$('html').hasClass('ie8')) {

        // collapse workaround for legacy IE
        $('[data-toggle="collapse"]').click(function () {
            var $target;
            if ($(this).data('target')) {
                $target = $($(this).data('target'));
            } else {
                $target = $($(this).attr('href'));
            }

            $target.collapse('toggle');

        });
    }

    // view more link for filter options
    $('.filterOptions').each(function () {
        $this = $(this);
        var $list = $this.find('>ul');
        var $items = $list.find('>li');
        if ($items.length > 10) {
            var heightAll = 30 * $items.length + 10;
            var heightTen = 280;
            var $viewMore = $('<a class="viewMore" href="#"><span>查看更多</span></a>');
            $this.append($viewMore);
            $list.css({
                height: '280px',
                overflow: 'hidden'
            });
            $viewMore.on('click', function (e) {
                e.preventDefault();

                if ($list.hasClass('all')) {
                    $list.animate({ height: heightTen }, 'slow');
                    $viewMore.find('span').text('查看更多');
                } else {
                    $list.animate({ height: heightAll }, 'slow');
                    $viewMore.find('span').text('收起更多');
                }
                $list.toggleClass('all');
            });
        }
    });

    // init affix effect for nav in product details page
    if ($('.productDetailsNav').length) {
        var $productDetailsNav = $('.productDetailsNav');
        $productDetailsNav.affix({
            offset: {
                top: $('.productDetailsNav').offset().top - window.screen.height,
                bottom: 1551
            }
        });

        //enable scrollspy
        $('body').scrollspy({ target: '#productDetailsNavLinks', offset: 200 });

        $('.nav-tabs li a').click(function (e) {
            e.preventDefault();
            $(this).tab('show');

            // If we are showing the scrollspy tab, let the
            // plugin refresh itself so it can function properly
            if ($(this).hasClass('enableScrollBy')) {
                $productDetailsNav.find('.navLinks .active').removeClass('active');
                $productDetailsNav.find('.navLinks a[href="' + $(this).attr('href') + '"]').parent().addClass('active');
            }
        });

        $productDetailsNav.find('.navLinks a').off('click').on('click', function (e) {
            e.preventDefault();
            var $this = $(this),
				href = $this.attr('href'),
				$href = $(href),
				$target = $this.hasClass('enableTab') ? $href.closest('[role="tabpanel"]') : $href;

            if ($(this).hasClass('enableTab')) {
                $target = $href.closest('div[role="tabpanel"]');
                var $tabNav = $target.find('.nav-tabs a[href="' + href + '"]');

                $tabNav.tab('show');

                $productDetailsNav.affix('checkPosition');
            }

            $('body,html').animate({
                scrollTop: $target.offset().top - 150
            }, 500, function () {
                $productDetailsNav.find('.navLinks .active').removeClass('active');
                $this.parent().addClass('active');
            });

            // $productDetailsNav.find('.navLinks .active').removeClass('active');
            // $(this).parent().addClass('active');

            return false;

        });
    }

    $('.pageNav').affix({
        offset: {
            top: ($('.pageNav').length ? $('.pageNav').offset().top : 0) - 150,
            bottom: 710
        }
    });

    $('#modalPersonaliseApplySuccess').on('show.bs.modal', function (event) {
        $('#modalPersonaliseApplyDetails').modal('hide');
    });

    $('#modalPersonaliseApplySuccess').on('show.bs.modal', function (event) {
        $('#modalBookNow').modal('hide');
    });

    $(document).on('mouseenter', '.promotionMark',function (event) {
        $(this).next().collapse('show');
    }).on('mouseleave', '.promotionMark', function (event) {
        $(this).next().collapse('hide');
    })

    // 价格日历可选择功能
    $('.priceCalendar .calendar td.selectable').on('click', function (e) {
        pDate
        var $this = $(this);
        var $table = $this.closest('table');
        $table.find('td.selected').removeClass('selected');
        $this.addClass('selected');
    })


    // close parent modal
    $(document).on('show.bs.modal', function (event) {
        if ($(event.relatedTarget).parents('.modal').length > 0) {
            setTimeout(function () {
                $(document.body).addClass('modal-open');
            }, 500)

        };
    });

	//$(document).on('DOMMouseScroll mousewheel scroll', function (e) {
	//    if ($('.modal:visible').length && $('.datepicker.datepicker-dropdown').length) {
	//        $('.datepicker.datepicker-dropdown').remove();
	//    }
	//});
});
